<?php
namespace app\api\controller;
use app\api\validate\AdminValidate;
use app\common\controller\ApiAdminBase;
use app\common\helpers\Functions;
use think\facade\Request;
use app\common\model\Admin as AdminModel;

class Admin extends ApiAdminBase
{
    /**
     * @api {post} /admin/login 后台登录
     * @apiName login
     * @apiGroup admin
     *
     * @apiParam {String{32位}}    admin_name        管理员名/管理员号码
     * @apiParam {String{32位}}    admin_password    管理员密码
     * @apiSuccessExample {json} 成功返回:
     *     {
     *         "data": [
     *         ],
     *         "code": 200,
     *         "msg": null
     *     }
     */
    public function login(Request $request){
        $input = $request::param();
        $validate = new AdminValidate();
        $validate->checkLogin();
        if( !$validate->check($input) ){
            return $this->reply(null,1001,$validate->getError());
        }

        $admin_name = $input['admin_name'];
        $admin_password = $input['admin_password'];

        $password = md5(md5($admin_password).$admin_password.config('app.private_key'));
        $data = AdminModel::where(['admin_name'=>$admin_name,'admin_password'=>$password])->find();


        $code = 200;
        if(empty($data)){
            $code = 1101;
        }else{
            $data = $data->toArray();
            $data['admin_id'] = $data['id'];
            unset($data['admin_password']);

            // 设置 session
            session('admin_user', $data);
            session('admin_user_sign', Functions::dataAuthSign($data));
        }
        return $this->reply($data,$code);
    }

    /**
     * @api {post} /admin/logout 后台退出
     * @apiName logout
     * @apiGroup admin
     *
     * @apiParam {String{32位}}    admin_name        管理员名/管理员号码
     * @apiParam {String{32位}}    admin_password    管理员密码
     * @apiSuccessExample {json} 成功返回:
     *     {
     *         "data": [
     *         ],
     *         "code": 200,
     *         "msg": null
     *     }
     */
    public function logout(Request $request){
        $code = 200;
        $data = null;
        // 设置 session
        session('admin_user', $data);
        session('admin_user_sign', $data);
        return $this->reply($data,$code);
    }

}